package com.oa.official.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oa.official.common.component.MinioComponent;
import com.oa.official.entity.process.ProcessTemplate;
import com.oa.official.response.Result;
import com.oa.official.service.OaProcessTemplateService;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 审批模板 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2023-02-14
 */
@RestController
@RequestMapping(value = "/admin/process/processTemplate")
@CrossOrigin
public class OaProcessTemplateController {

    @Resource
    private OaProcessTemplateService oaProcessTemplateService;

    //分页查询审批模板
    @ApiOperation("获取分页审批模板数据")
    @GetMapping("/{page}/{limit}")
    public Result index(@PathVariable Long page,
                        @PathVariable Long limit) {
        Page<ProcessTemplate> pageParam = new Page<>(page,limit);
        //分页查询审批模板，把审批类型对应名称查询
        IPage<ProcessTemplate> pageModel = oaProcessTemplateService.selectPageProcessTemplate(pageParam);
        return Result.success(pageModel);
    }

    //@PreAuthorize("hasAuthority('bnt.processTemplate.list')")
    @ApiOperation(value = "获取")
    @GetMapping("/get/{id}")
    public Result get(@PathVariable Long id) {
        ProcessTemplate processTemplate = oaProcessTemplateService.getById(id);
        return Result.success(processTemplate);
    }

    //@PreAuthorize("hasAuthority('bnt.processTemplate.templateSet')")
    @ApiOperation(value = "新增")
    @PostMapping("/save")
    public Result save(@RequestBody ProcessTemplate processTemplate) {
        oaProcessTemplateService.save(processTemplate);
        return Result.success();
    }

    //@PreAuthorize("hasAuthority('bnt.processTemplate.templateSet')")
    @ApiOperation(value = "修改")
    @PutMapping("/update")
    public Result updateById(@RequestBody ProcessTemplate processTemplate) {
        oaProcessTemplateService.updateById(processTemplate);
        return Result.success();
    }

    //@PreAuthorize("hasAuthority('bnt.processTemplate.remove')")
    @ApiOperation(value = "删除")
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable Long id) {
        oaProcessTemplateService.removeById(id);
        return Result.success();
    }

    private static final String bucketName = "activiti7-oa-official-bucket";
    @Resource
    private MinioComponent minioComponent;


    @ApiOperation(value = "上传流程定义")
    @PostMapping("/uploadProcessDefinition")
    public Result uploadProcessDefinition(MultipartFile file) throws Exception {
//        //获取classes目录位置
//        String path = new File(ResourceUtils.getURL("classpath:")
//                          .getPath()).getAbsolutePath();
//        //设置上传文件夹
//        File tempFile = new File(path + "/processes/");
//        if(!tempFile.exists()) {
//            tempFile.mkdirs();
//        }
//        //创建空文件，实现文件写入
//        String filename = file.getOriginalFilename();
//        File zipFile = new File(path + "/processes/" + filename);
//        //保存文件
//        try {
//            file.transferTo(zipFile);
//        } catch (IOException e) {
//            return Result.error("系统错误");
//        }
//        Map<String, Object> map = new HashMap<>();
//        //根据上传地址后续部署流程定义，文件名称为流程定义的默认key
//        map.put("processDefinitionPath", "processes/" + filename);
//        assert filename != null;
//        map.put("processDefinitionKey", filename.substring(0, filename.lastIndexOf(".")));
//        return Result.success(map);
        //先创建桶(如果不存在的话)
        minioComponent.createBucket(bucketName);
        String uploadUrl = minioComponent.uploadFile(bucketName, file);
        //根据上传地址后续部署流程定义，文件名称为流程定义的默认key
        Map<String, Object> map = new HashMap<>();
        map.put("processDefinitionPath",uploadUrl);
        String filename = file.getOriginalFilename();
        assert filename != null;
        map.put("processDefinitionKey", filename.substring(0, filename.lastIndexOf(".")));
        return Result.success(map);
    }

    //部署流程定义（发布）
    @ApiOperation(value = "发布")
    @GetMapping("/publish/{id}")
    public Result publish(@PathVariable Long id) {
        //修改模板发布状态 1 已经发布
        //流程定义部署
        oaProcessTemplateService.publish(id);
        return Result.success();
    }

}

